#include <func.h>

void cleanup(void* p)
{
    free(p);
    printf("i am cleanup func\n");
}
void* pthread_func(void* p)
{
    char* q=(char*)malloc(20);
    pthread_cleanup_push(cleanup,q);
    printf("malloc success!\n");
    sleep(1);
    printf("start free!\n");
    pthread_exit(NULL);
    // pthread_cleanup_pop(1)
    pthread_cleanup_pop(0);//pop[1]弹出清理函数并执行，pop[0]弹出清理函数不执行
    return NULL;
}
//创建子线程后，子线程malloc空间，然后在free之前被cancel掉
int main()
{
    pthread_t pthid;
    int ret=pthread_create(&pthid,NULL,pthread_func,NULL);
    THREAD_ERROR_CHECK(ret,"pthread_create")
    //cancel时子线程并没有开始free对应的空间
    // ret=pthread_cancel(pthid);
    // THREAD_ERROR_CHECK(ret,"pthread_cancel")
    ret=pthread_join(pthid,NULL);
    THREAD_ERROR_CHECK(ret,"pthread_join")
    printf("i am main thread\n");
    return 0;
}